//
//  K_ROOMVC.m
//  K-Music
//
//  Created by CHUN on 16/1/23.
//  Copyright © 2016年 CHUN. All rights reserved.
//

#import "K_ROOMVC.h"
#import "K_ROOMCell.h"
#import "K_Mode.h"
#import "SameWay.h"
#import "Friends_see.h"
#import "K_HistoryVC.h"
#import "K_MyroomVC.h"
#import "K_RankingVC.h"
#import "RONGL.h"


@interface K_ROOMVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
{
    UICollectionView * ROOM ;
    
    NSMutableArray * all_Data ;
    
    UIView *searchView ;
    
    NSString * K_groupId;
    
}

@end

@implementation K_ROOMVC


- (void)loadView
{
    [super loadView];
    
    [self RONG_login];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"包房K歌";
    self.view.backgroundColor = RGB(241, 241, 241);
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"back" highIcon:@"back" target:self action:@selector(back_back)];
    
    
    [self creatUI];
    
}

-(void)creatUI{
    
    searchView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 50)];
    searchView.userInteractionEnabled = YES;
    searchView.backgroundColor=[UIColor whiteColor];
    
    UIImageView * HeaderView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 50)];
    UIImageView * View = [[UIImageView alloc]initWithFrame:CGRectMake(25, 10, WIDTH-50, 30)];
    HeaderView.backgroundColor = RGB(255, 255, 255);
    View.image = [UIImage imageNamed:@"search_icon2"];
    
    HeaderView.userInteractionEnabled = YES;
    
    UITapGestureRecognizer * PersonalTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(search)];
    
    [searchView addGestureRecognizer:PersonalTap];
    
    [searchView addSubview:View];
    
    [self.view addSubview:searchView];

    
    UIImageView * Image_View=[[UIImageView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(searchView.frame), WIDTH, 150)];
    Image_View.image = [UIImage imageNamed:@"rush_three"];
    [self.view addSubview:Image_View];

    NSArray*textData;
    
    textData=[NSArray arrayWithObjects:@"C_6",@"C_5",@"C_7",nil];
    
    NSArray*titleData=[NSArray arrayWithObjects:@"历史访问",@"我的房间",@"排行榜",nil];
    
    UIView *headview=[[UIView alloc]initWithFrame:CGRectMake(0,  CGRectGetMaxY(Image_View.frame), WIDTH, 100)];
    headview.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:headview];
    
    for (int i=0; i<3; i++) {
        
        UIImageView*img=[[UIImageView alloc]init];
        img.frame = CGRectMake((WIDTH/6-30)+WIDTH/3*i, 10, 60, 60);
        img.image=[UIImage imageNamed:[NSString stringWithFormat:@"%@",textData[i]]];
        [headview addSubview: img];
        
        UILabel*text=[[UILabel alloc]initWithFrame:CGRectMake(i*WIDTH/3, CGRectGetMaxY(img.frame)+5, WIDTH/3, 20)];
        text.textAlignment=NSTextAlignmentCenter;
        text.text=[NSString stringWithFormat:@"%@",titleData[i]];
        [headview addSubview: text];
        
        UIButton*img_btn=[UIButton buttonWithType:UIButtonTypeCustom];
        img_btn.frame=CGRectMake(i*WIDTH/3, 0, WIDTH/3, HEIGHT/10 );
        img_btn.tag=i ;
        [img_btn addTarget:self action:@selector(TopButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [headview addSubview:img_btn];
        
    }
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    
    
    ROOM=[[UICollectionView alloc]initWithFrame:CGRectMake(0,CGRectGetMaxY(headview.frame)+10 , WIDTH  , HEIGHT- CGRectGetMaxY(headview.frame)-10-64)collectionViewLayout:flowLayout];
    ROOM.delegate=self;
    ROOM.dataSource=self;
    ROOM.backgroundColor=[UIColor whiteColor];
    
    [ROOM registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader  withReuseIdentifier:@"WHScrollAndPageView"];
    [self.view addSubview:ROOM];
    
}

- (void)search
{
    Friends_see * see = [[Friends_see alloc]init];
    see.navigationItem.title = @"搜索房间";
    [self.navigationController pushViewController:see animated:YES];
}


-(void)SearchAction{
    
    [self.view endEditing:YES];
    
    [MBProgressHUD showErrorWithStatus:@"暂无数据" toView:self.view];
}

-(void)TopButtonClick:(UIButton*)btn{
    
    if (btn.tag==0) {
        
        K_HistoryVC * history = [[K_HistoryVC alloc]init];
        [self.navigationController pushViewController:history animated:YES];
        NSLog(@"历史访问");
        history.hidesBottomBarWhenPushed = YES;
        
    
    
    }else if(btn.tag==1)
    {
        K_MyroomVC * room = [[K_MyroomVC alloc]init];
        [self.navigationController pushViewController:room animated:YES];
        room.hidesBottomBarWhenPushed = YES;
         NSLog(@"我的房间");
    }
    
    else if(btn.tag==2)
    {
         NSLog(@"排行榜");
    
//        NSArray * viewControllers = @[[K_RankingVC class], [K_RankingTWO class],[K_RankingThree class]];
//        
//        NSArray *titles = @[@"人气榜",@"礼物榜",@"财富榜"];
//        
//        WMPageController *pageVC = [[WMPageController alloc] initWithViewControllerClasses:viewControllers andTheirTitles:titles];
//        pageVC.viewFrame = CGRectMake(0, 0, WIDTH, HEIGHT);
//        pageVC.pageAnimatable = YES;
//        pageVC.menuItemWidth = 100;
//        pageVC.menuHeight = 50;
//        pageVC.titleSizeSelected = 15;
//        pageVC.titleColorSelected = [UIColor orangeColor];
//        pageVC.postNotification = YES;
//        pageVC.bounces = YES;
//        pageVC.menuViewStyle = WMMenuViewStyleLine;
//        pageVC.hidesBottomBarWhenPushed = YES;
//        
//        pageVC.navigationItem.title = @"排行榜";
//        pageVC.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"back" highIcon:@"back" target:self action:@selector(back_back)];
//        [self.navigationController pushViewController:pageVC animated:NO];
//        pageVC.hidesBottomBarWhenPushed = YES;
        
        
        [self.navigationController pushViewController:[K_RankingVC new] animated:NO];
//        pageVC.hidesBottomBarWhenPushed = YES;
        
    }
    

}

- (void)back_back
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return [User_information conversion].KROOM_Data.count;
    
}

 - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
 {
     CGSize size = CGSizeMake(WIDTH, 50);
     return size;
 }
 
 
 -(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
 
    UIView *View = [[UIView alloc]init];
    View.backgroundColor = [UIColor whiteColor];
    View.userInteractionEnabled = YES;
    
    UIButton *butt = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 50)];
    butt.backgroundColor = [UIColor whiteColor];
    [butt addTarget:self action:@selector(ppp:) forControlEvents:(UIControlEventTouchUpInside)];
    [View addSubview:butt];
    
    UILabel * name = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, WIDTH/2, 50)];
    
    name.text = @"|  热门包房";
    name.textColor=[UIColor orangeColor];
    name.textAlignment=NSTextAlignmentLeft;
    [View addSubview: name];
    
    
    UILabel * more = [[UILabel alloc]initWithFrame:CGRectMake( WIDTH-100 , 0, 80, 50)];
    more.text = @"全部 >>";
    more.textColor=[UIColor orangeColor];
    more.textAlignment=NSTextAlignmentRight;
    [View addSubview:more];
 
     if (kind == UICollectionElementKindSectionHeader){
     UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"WHScrollAndPageView" forIndexPath:indexPath];
     headerView.backgroundColor = [UIColor redColor];
     [headerView addSubview:View];
     return headerView;
     
     }else{
     
     return nil;
         
     }
}

-(void)ppp:(UIButton*)button{
    
    NSLog(@"1-%ld",(long)button.tag);
    
}


-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    [ROOM registerClass:[K_ROOMCell class] forCellWithReuseIdentifier:@"K_ROOMCell"];
    
    K_ROOMCell*cell=(K_ROOMCell*)[collectionView dequeueReusableCellWithReuseIdentifier:@"K_ROOMCell" forIndexPath:indexPath];
    
    K_Mode * data =[[K_Mode alloc]init];
    
    data  = [User_information conversion].KROOM_Data[indexPath.row];

    cell.mylabel.text=[NSString stringWithFormat:@"%@ 人",data.peopleNumber];
    
    cell.my_name.text=[NSString stringWithFormat:@"%@",data.descriptionD];
    
    cell.room_num_label.text=[NSString stringWithFormat:@"%@",data.groupId];
    
    [cell.dt sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",data.pictureUrl]]];

    
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    NSLog(@"%ld",indexPath.row);

    K_Mode * data =[[K_Mode alloc]init];
    
    data  = [User_information conversion].KROOM_Data[indexPath.row];
    
    NSLog(@"%@",data.voiceId);
    NSLog(@"%@",data.groupId);
    
    K_groupId = [NSString stringWithFormat:@"%@",data.groupId];
    
//    [self joinGroup:data.groupId withReason:nil];
    
    NSString * roomID;
    if (data.voiceId.length < 30) {
        roomID = data.voiceId;
    }
    else
    {
        roomID = [data.voiceId substringToIndex:30];
    }
  
    NSLog(@"%@",roomID);

    ECMultiVoiceMeetingRoom * selectRoom = [self.rong_room_Dic objectForKey:roomID];
    
    self.curSelectRoom = selectRoom;
    if(selectRoom.roomNo.length > 0  && selectRoom.square > selectRoom.joinNum) {
        
        BOOL iscreator = NO;
        if ([selectRoom.creator isEqualToString:[DemoGlobalClass sharedInstance].userName]) {
            iscreator = YES;
        }
        
        if (iscreator) {
            UIActionSheet *menu = [[UIActionSheet alloc]
                                   initWithTitle: @"选择"
                                   delegate:self
                                   cancelButtonTitle:nil
                                   destructiveButtonTitle:nil
                                   otherButtonTitles:@"IP加入会议",@"解散会议",@"管理会议",@"取消",nil];
            [menu setCancelButtonIndex:3];
            menu.tag = 1000;
            [menu showInView:self.view.window];
            
        } else {
            
            if (selectRoom.isValidate) {
                [self showIpuntPassWord];
            } else {
                
                
                [self joinChatroomInRoomWithSelectRoom:selectRoom andPwd:nil isJoin:YES];
                
//                [self joinGroup:data.groupId withReason:nil];
            
            
                
                
            }
        }
    }
}

-(void)joinGroup:(NSString*)groupId withReason:(NSString*)reason
{
    
    MBProgressHUD* hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"请稍等...";
    hud.removeFromSuperViewOnHide = YES;
    
    __weak __typeof(self)weakSelf = self;
    [[ECDevice sharedInstance].messageManager joinGroup:groupId reason:reason completion:^(ECError *error, NSString *groupId) {
        
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [MBProgressHUD hideHUDForView:strongSelf.view animated:NO];
        strongSelf.applyGroup.mode == ECGroupPermMode_DefaultJoin;
        
        if (error.errorCode==ECErrorType_Have_Joined) {

            [DeviceDelegateHelper sharedInstance].sessionId = groupId;
            ChatViewController * chatView = [[ChatViewController alloc] initWithSessionId:strongSelf.applyGroup.groupId];
            
//            [strongSelf.navigationController setViewControllers:[NSArray arrayWithObjects:[strongSelf.navigationController.viewControllers objectAtIndex:0],chatView, nil] animated:YES];
            
        }else if(error.errorCode==ECErrorType_NoError){
            if (strongSelf.applyGroup.mode == ECGroupPermMode_DefaultJoin) {
                ChatViewController * chatView = [[ChatViewController alloc] initWithSessionId:strongSelf.applyGroup.groupId];
#warning 所有用户都默认  加入
                strongSelf.applyGroup.mode == ECGroupPermMode_DefaultJoin;
//                [strongSelf.navigationController setViewControllers:[NSArray arrayWithObjects:[strongSelf.navigationController.viewControllers objectAtIndex:0],chatView, nil] animated:YES];
            }else{
                [strongSelf showToast:@"申请加入已发出，请等待群主同意请求"];
            }
        } else {
            NSString* detail = error.errorDescription.length>0?[NSString stringWithFormat:@"\rerrorDescription:%@",error.errorDescription]:@"";
            [strongSelf showToast:[NSString stringWithFormat:@"errorCode:%d%@",(int)error.errorCode,detail]];
        }
    }];
}


-(void)showIpuntPassWord {
    
    UIAlertView *alertView = alertView = [[UIAlertView alloc] initWithTitle:@"输入密码" message:@"该聊天室设置了身份验证, 请输入密码" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alertView.alertViewStyle = UIAlertViewStylePlainTextInput;
    UITextField *textField = [alertView textFieldAtIndex:0];
    textField.tag = TAG_ALERTVIEW_ChatroomPwd;
    textField.placeholder = @"请输入密码";
    [alertView show];
}

-(void)joinChatroomInRoomWithSelectRoom:(ECMultiVoiceMeetingRoom*) selectRoom andPwd:(NSString*) pwd isJoin:(BOOL)isJoin {
    
    [self joinGroup:K_groupId withReason:nil];
    
    BOOL iscreator = NO;
    if ([selectRoom.creator isEqualToString:[DemoGlobalClass sharedInstance].userName]) {
        iscreator = YES;
    }
    
    K_ROOM_ChatController *chatroomview = [[K_ROOM_ChatController alloc] initWithSessionId:K_groupId];
    
    chatroomview.navigationItem.hidesBackButton = YES;
    chatroomview.roomname = selectRoom.roomName;
    chatroomview.backView = self;
    chatroomview.isCreator = iscreator;
    chatroomview.curChatroomId = selectRoom.roomNo;
    chatroomview.isJoin = isJoin;
    [self.navigationController pushViewController:chatroomview animated:YES];
    
    if (isJoin) {
        [chatroomview joinChatroomInRoom:selectRoom.roomNo andPwd:pwd];
    }
}





//定义每一个cell大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGSize size;

    return CGSizeMake(WIDTH/2-2, HEIGHT/4);
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 1;
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 1;
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




#pragma mark -容联登陆-
- (void)RONG_login
{
    //是否有登录信息
    [DemoGlobalClass sharedInstance].isAutoLogin = [self getLoginInfo];
    if ([DemoGlobalClass sharedInstance].isAutoLogin) {
        //打开本地数据库
        [[DeviceDBHelper sharedInstance] openDataBasePath:[DemoGlobalClass sharedInstance].userName];
        self.mainView = [[MainViewController alloc] init];
        [self.navigationController pushViewController:self.mainView animated:YES];
        //        rootView = [[UINavigationController alloc] initWithRootViewController:_mainView];
    } else {
        
        //        self.loginView = [[LoginViewController alloc] init];
        //       [self.navigationController pushViewController:self.loginView animated:YES];
        //        rootView = [[UINavigationController alloc] initWithRootViewController:_loginView];
        
        [self nextBtnClicked];
    }
    
}

-(BOOL)getLoginInfo {
    
    NSString *loginInfo = [DemoGlobalClass sharedInstance].userName;
    if (loginInfo.length>0) {
        return YES;
    }
    return NO;
}

#pragma mark -登陆-
-(void)nextBtnClicked {
    
    NSCharacterSet *ws = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    _userName = [[UITextField alloc]init];
    _userName.text = [NSString stringWithFormat:@"%@",[FileStorage NSUserDefault_getObjectForKey:User_id]];
    NSString *trimmed = [_userName.text stringByTrimmingCharactersInSet:ws];
    
    //校验账号是否为手机号
    //    NSString* errormessage = [LoginViewController valiMobile:trimmed];
    
    if (trimmed.length == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"容联账号为空" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    if (trimmed.length>0)
    {
        [self.view endEditing:YES];
        
        [[NSUserDefaults standardUserDefaults] setObject:trimmed forKey:@"lasttimeuser"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        NSString *userName = trimmed;
        NSString *password = nil;
        //[_password.text stringByTrimmingCharactersInSet:ws];
        
        ECLoginInfo * loginInfo = [[ECLoginInfo alloc] init];
        loginInfo.username = userName;
        loginInfo.userPassword = password;
        loginInfo.appKey = [DemoGlobalClass sharedInstance].appKey;
        loginInfo.appToken = [DemoGlobalClass sharedInstance].appToken;
        loginInfo.authType = [DemoGlobalClass sharedInstance].loginAuthType;
        loginInfo.mode = LoginMode_InputPassword;
        
        __weak typeof(self) weakself = self;
        MBProgressHUD* hud = [MBProgressHUD showHUDAddedTo:weakself.view animated:YES];
        hud.labelText = @"正在登录...";
        hud.removeFromSuperViewOnHide = YES;
        
        [DemoGlobalClass sharedInstance].userPassword = password;
        [[DeviceDBHelper sharedInstance] openDataBasePath:userName];
        [DemoGlobalClass sharedInstance].isHiddenLoginError = NO;
        [[ECDevice sharedInstance] login:loginInfo completion:^(ECError *error){
            
            //            [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_onConnected object:error];
            //            if (error.errorCode == ECErrorType_NoError) {
            //                [DemoGlobalClass sharedInstance].userName = userName;
            //            }
            //
            //            __strong typeof(weakself) strongSelf = weakself;
            [MBProgressHUD hideHUDForView:weakself.view animated:YES];
            
            [self LoginSuccess];
            
        }];
    }
}

//登录成功，页面跳转
-(void)LoginSuccess
{
    NSLog(@"容连登陆成功");
    //获取所有房间
    [self getMultiVoiceMeetingRoomFromService];
    
}

- (void)getMultiVoiceMeetingRoomFromService {
    
    MBProgressHUD* hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"请稍后...";
    hud.removeFromSuperViewOnHide = YES;
    
    __weak __typeof(self) weakSelf = self;
    [[ECDevice sharedInstance].meetingManager listAllMultMeetingsByMeetingType:ECMeetingType_MultiVoice andKeywords:nil completion:^(ECError *error, NSArray *meetingList) {
        
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [MBProgressHUD hideHUDForView:strongSelf.view animated:YES];
        if (error.errorCode == ECErrorType_NoError) {
        
            strongSelf.chatroomsArray = [meetingList copy];
            
            [self Arr_Chang_Dic];
    
        } else {
            NSString* detail = error.errorDescription.length>0?[NSString stringWithFormat:@"\rerrorDescription:%@",error.errorDescription]:@"";
            [strongSelf showToast:[NSString stringWithFormat:@"errorCode:%d%@",(int)error.errorCode,detail]];
        }
        
    }];
}
- (void)Arr_Chang_Dic
{
    self.rong_room_Dic = [[NSMutableDictionary alloc]init];
    for (int i = 0 ; i< self.chatroomsArray.count; i++) {
        ECMultiVoiceMeetingRoom *roomInfo = [self.chatroomsArray objectAtIndex:i];
        [self.rong_room_Dic setObject:[self.chatroomsArray objectAtIndex:i] forKey:roomInfo.roomNo];
//        NSLog(@"%d",i);
//        NSLog(@"%@",roomInfo.roomNo);
    }
    NSLog(@"%@",self.rong_room_Dic);
}
//Toast错误信息
-(void)showToast:(NSString *)message {
    MBProgressHUD* hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.labelText = message;
    hud.margin = 10.f;
    hud.removeFromSuperViewOnHide = YES;
    [hud hide:YES afterDelay:2];
}




@end
